package com.bwie.common.exception;

import com.bwie.common.result.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalException {
    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result business(BusinessException e){
        String msg = e.getResult().getMsg();
        return Result.error(msg);
    }
    /**
     * 全局异常
     */
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e){
        String message = e.getMessage();
        return Result.error(message);
    }
    /**
     * 参数异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArg(MethodArgumentNotValidException e){
        //获取所有异常
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        //初始化存入异常
        StringBuilder stringBuilder = new StringBuilder();
        for (ObjectError allError : allErrors) {
            String defaultMessage = allError.getDefaultMessage();
            stringBuilder.append(defaultMessage).append(";");
        }
        return Result.error(stringBuilder);
    }
}
